// 用户相关的数据
import { reqlogin } from '@/api/user'
// import { reqlogin, logout, getInfo } from '@/api/user'
import { localremovetoken, localsettoken, localgettoken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { loginlog } from '@/api/log'
// import store from '@/store'
const getDefaultState = () => {
  return {
    token: JSON.parse(localgettoken()) || '',
    // token: JSON.parse(getToken()) || '',
    name: '',
    nameNo: '',
    currentAlias: '',
    buttons: JSON.parse(localStorage.getItem('buttons')) || []
    // buttons: ['main-task-create', 'main-task-delete', 'main-task-finish', 'main-task-reset']
    // avatar: 'https://mayiyi-1310833442.cos.ap-nanjing.myqcloud.com/110cat.jpeg'
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  // 修改token信息
  SET_TOKEN: (state, newtoken) => {
    // 将token 保存在 store
    state.token = newtoken
    state.nameNo = newtoken.userNo
    // console.log(newtoken.menus)
    // console.log(newtoken.menus[1].child[1].child.length > 0)
    // 将token保存在本地
    // setToken(newtoken)
    // const new2token = {
    //   roleId: newtoken.roleId,
    //   userName: newtoken.userName,
    //   userNo: newtoken.userNo
    // }
    localsettoken(JSON.stringify(newtoken))

    const childClick = JSON.parse(localgettoken())
    childClick.menus.forEach(item => {
      item.child.forEach(value => {
        // console.log(value)
        if (value.child.length > 0) {
          // console.log(value)
          value.child.forEach(data => {
            // console.log(data.menuUrl)
            state.buttons.push(data.menuUrl)
          })
        }
      })
    })
    // console.log(state.buttons, 'buttons', JSON.parse(localgettoken()))
    localStorage.setItem('buttons', JSON.stringify(state.buttons))
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // 登录请求
  async login(context, obj) {
    // 写法一
    // const res = await reqlogin(obj)
    // console.log(res.data)
    // context.commit('SET_TOKEN', res.data)

    // 写法二
    return new Promise((resolve, reject) => {
      reqlogin(obj).then(async (res) => {
        // console.log(res.data, 111111111)
        context.commit('SET_TOKEN', res.data)
        // console.log(state.token) // 拿到数据
        // 登录操作（异步）成功了后 调用成功函数  promise就会成功
        // console.log(JSON.parse(localgettoken()), 222222222)
        resolve(res)
        // const token = store.getters.token
        // const otherRoutes = await store.dispatch('permission/filterRoutes', token.menus)
        // router.addRoutes([
        //   ...otherRoutes,
        //   { path: '*', redirect: '/404', hidden: true }
        // ])
      }).catch((error) => {
        // 登录操作（异步）失败了后 调用失败函数  promise就会失败
        reject(error)
      })
    })
  },
  // user login
  // login({ commit }, userInfo) {
  //   const { username, password } = userInfo
  //   return new Promise((resolve, reject) => {
  //     login({ username: username.trim(), password: password }).then(response => {
  //       const { data } = response
  //       console.log(data, 123456555)
  //       commit('SET_TOKEN', data)
  //       setToken(data)
  //       resolve()
  //     }).catch(error => {
  //       console.log(error)
  //       reject(error)
  //     })
  //   })
  // },

  // get user info
  /*  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { name, avatar } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  }, */

  // 拿到用户信息
  async getInfo(context, state) {
    const data = await loginlog({})
    // console.log(data, '登录日志的数据测试')
    context.commit('SET_NAME', data.count)
    // 在async函数中 return 结果 相对于 之前的promise里 resolve(结果)
    return data
  },
  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
      localremovetoken() // must remove  token  first
      resetRouter()
      localStorage.removeItem('buttons')
      commit('RESET_STATE')
      resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      localremovetoken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

